package com.yidushishizijie;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
* 使用lock取代synchroized
* 使用Condition取代Object method(wait,nodify,and nodifyAll)
* */
public class NewThreadWaitNodifyDemo {
    public static void main(String[] args) {
        AirCondition03 airCondition03 = new AirCondition03();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition03.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() ->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition03.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

class AirCondition03{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increase() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while(number != 0){
                condition.await();
            }
            //操作
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void decrease() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while(number == 0){
                condition.await();
            }
            //操作
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //通知
            condition.signalAll();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
